package com.trainoo.novel.crawler;

import com.trainoo.novel.constant.NovelConstant;
import com.trainoo.novel.model.Book;
import com.trainoo.novel.model.Chapter;
import com.trainoo.novel.util.UrlDownLoader;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.regex.Pattern;

/**
 * Created by Administrator on 2018/8/18.
 * BQG 转码适配器
 */
@Component
public class BqgNovelCrawler extends NovelCrawlerAdapter {

    private static Logger logger = LoggerFactory.getLogger(BqgNovelCrawler.class);

    @Value("${base.url.bqg}")
    private String BASE_URL;

    @Value("${search.url.bqg}")
    private String SEARCH_URL;

    @Override
    public Book crawlBookInfo(String bookId) {
        // 返回结果集
        Book book = new Book();

        Document doc = UrlDownLoader.download(BASE_URL + bookId);
        Element main = doc.getElementById("maininfo");
        String mainInfo = main.html();
        String bookName = main.getElementsByTag("h1").html();
        book.setMainInfo(mainInfo);
        book.setBookName(bookName);

        Elements lists = doc.getElementById("list").getElementsByTag("dd");
        List<Chapter> chapters = new ArrayList<>();
        for (Element e : lists){
            String chapUrl = e.getElementsByTag("a").attr("href");
            String chapName = e.getElementsByTag("a").text();
            chapUrl = "/book/" + chapUrl.replace(BASE_URL, "");
            Chapter chapter = new Chapter();
            chapter.setChapName(chapName);
            chapter.setChapUrl(chapUrl);
            chapters.add(chapter);
        }
        book.setChapters(chapters);
        return book;
    }

    @Override
    public Chapter readChapter(String url) {
        Document doc =  UrlDownLoader.download(BASE_URL + url);
        String title = doc.getElementsByClass("bookname").first().getElementsByTag("h1").text();
        String content = doc.getElementById("content").html();
        Element bottom = doc.getElementsByClass("bottem2").first();
        String prev = bottom.getElementsByTag("a").get(1).attr("href").replace(BASE_URL, "/book/");
        String chapMain = bottom.getElementsByTag("a").get(2).attr("href").replace(BASE_URL, "/book/");
        String next = bottom.getElementsByTag("a").get(3).attr("href").replace(BASE_URL, "/book/");

        Chapter chapter = new Chapter();
        chapter.setPreUrl(prev);
        chapter.setChapMain(chapMain);
        chapter.setNextUrl(next);
        chapter.setChapName(title);
        chapter.setContent(content);
        logger.info("正在加载内容[{}]", title);
        return chapter;
    }

    @Override
    public List<Chapter> hotBookList() {
        Document doc =  UrlDownLoader.download(BASE_URL);
        Elements aList = doc.getElementsByTag("a");
        List<Chapter> hotList = new ArrayList<>();
        Set<String> urls = new HashSet<>();
        for (int i = 0; i < aList.size(); i++) {
            String html = aList.get(i).html();
            String href = aList.get(i).attr("href").replace(BASE_URL, "/book/");
            String regex = "[0-9]{1,2}_[0-9]+";
            boolean isBook = Pattern.compile(regex).matcher(href).find();
            if (isBook && !html.contains("img") && !href.contains(".html")){
                // 使用set去重
                if(urls.add(href)){
                    hotList.add(new Chapter(html, href));
                }
            }
        }
        return hotList;
    }

    @Override
    public List<Book> searchBook(Map<String, String> contentMap) {

        String url = SEARCH_URL + formatUri(contentMap.get(NovelConstant.KEY_WORD));
        Document doc = UrlDownLoader.download(url);
        Element tBody = doc.getElementById("hotcontent").getElementsByTag("tbody").first();
        Elements trs = tBody.getElementsByTag("tr");

        List<Book> resultList = new ArrayList<>();
        // 因为第0个是表格标题，所以从第1个开始遍历
        for (int i = 1; i < trs.size(); i++){
            Element e = trs.get(i);

            String bookUrl = e.getElementsByTag("td").get(0).getElementsByTag("a").first().attr("href");
            String bookName = e.getElementsByTag("td").get(0).getElementsByTag("a").first().text();
            String newUrl = e.getElementsByTag("td").get(1).getElementsByTag("a").first().attr("href");
            String newName = e.getElementsByTag("td").get(1).getElementsByTag("a").first().text();
            String authName = e.getElementsByTag("td").get(2).text();
            String bookDesc = e.getElementsByTag("td").get(5).text();

            Book book = new Book();
            bookUrl = bookUrl.replace(BASE_URL, "").replace("/", "");
            book.setBookUrl("/book/" + bookUrl);
            book.setBookName(bookName);
            book.setNewUrl("/book/" + bookUrl + newUrl
                    .substring(newUrl.lastIndexOf("/"), newUrl.length()));
            book.setNewName(newName);
            book.setAuthName(authName);
            book.setBookDesc(bookDesc);

            resultList.add(book);
        }
        return resultList;
    }

    //格式： ?searchkey=ss
    private String formatUri(String keyWord) {
        return "?searchkey=" + keyWord;
    }
}
